package com.imooc.order.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.imooc.order.dao.OrderDetailDao;
import com.imooc.order.dto.OrderMessageDTO;
import com.imooc.order.enummeration.OrderStatus;
import com.imooc.order.po.OrderDetailPO;
import com.imooc.order.vo.OrderCreateVo;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeoutException;

/**
 * ProjectName order
 * 处理用户操作
 * @author xieyucan
 * <br>CreateDate 2022/9/20 13:46
 */
@Service
public class OrderService {

    private final OrderDetailDao orderDetailDao;

    /**
     * 用户序列化操作
     */
    private final ObjectMapper objectMapper;

    public OrderService(OrderDetailDao orderDetailDao, ObjectMapper objectMapper) {
        this.orderDetailDao = orderDetailDao;
        this.objectMapper = objectMapper;
    }

    public void createOrder(OrderCreateVo createVo) throws IOException, TimeoutException {
        //订单信息保存数据库
        OrderDetailPO orderDetailPO = new OrderDetailPO();
        orderDetailPO.setAccountId(createVo.getAccountId());
        orderDetailPO.setAddress(createVo.getAddress());
        orderDetailPO.setProductId(createVo.getProductId());
        orderDetailPO.setStatus(OrderStatus.ORDER_CREATING);
        orderDetailPO.setDate(new Date());
        orderDetailDao.insert(orderDetailPO);
        //向餐厅微服务发送mq
        OrderMessageDTO orderMessageDTO = new OrderMessageDTO();
        orderMessageDTO.setOrderId(orderDetailPO.getId());
        orderMessageDTO.setProductId(orderDetailPO.getProductId());
        orderMessageDTO.setAccountId(orderDetailPO.getAccountId());

        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("43.138.244.235");
        connectionFactory.setPort(5672);
        connectionFactory.setPassword("1234");
        connectionFactory.setUsername("admin");


        try(Connection connection=connectionFactory.newConnection();
            Channel channel=connection.createChannel()){
            String messageToSend=objectMapper.writeValueAsString(orderMessageDTO);

            channel.basicPublish(
                    "exchange.order.restaurant",
                    "key.restaurant",
                    null,
                    messageToSend.getBytes()
            );
        }
    }
}
